package com.lagou.service.com.lagou.zookeeper;

import org.I0Itec.zkclient.ZkClient;

import java.util.List;

public class ZooKeeperServiceDiscovery implements ServiceDiscovery {

    private final static String ZK_REGISTRY_PATH = "/zk-rpc-server";

    private static ZkClient zkClient;

    public ZooKeeperServiceDiscovery(String zkAddress) {
        if(zkClient == null){
            // 创建 ZooKeeper 客户端
            zkClient = new ZkClient(zkAddress);
            System.out.println("connect zookeeper");
        }
    }

    @Override
    public String discover(String name) {

        try {
            // 获取 service 节点
            String servicePath = ZK_REGISTRY_PATH + "/" + name;
            if (!zkClient.exists(servicePath)) {
                throw new RuntimeException(String.format("can not find any service node on path: %s", servicePath));
            }
            List<String> addressList = zkClient.getChildren(servicePath);
            if (addressList == null || addressList.size() == 0) {
                throw new RuntimeException(String.format("can not find any address node on path: %s", servicePath));
            }
            // 获取 address 节点
            String address = null;
            // 响应时间最短的服务端信息
            String serviceAddressTemp = null;

            int size = addressList.size();
            if (size == 1) {
                // 若只有一个地址，则获取该地址
                address = addressList.get(0);
                System.out.println("get only address node: "+ address);
            } else {

                Integer responseTime = null;
                for(String add : addressList){
                    String addressPath = servicePath + "/" + add;
                    String serviceAddress = zkClient.readData(addressPath);
                    if(serviceAddress != null){
                        String responseInfo = null;
                        try {
                            responseInfo = zkClient.readData(servicePath + "-response/" + serviceAddress);
                        }catch (Exception ex){
                            System.out.println("未活动到responseInfo :"+servicePath + "-response/" + serviceAddress);
                        }

                        if(responseInfo == null){
                            return serviceAddress;
                        }
                        String[] responseInfos = responseInfo.split(":");

                        int responseTimeTemp = Integer.parseInt(responseInfos[0]);
                        if(serviceAddressTemp == null && responseTime == null){
                            serviceAddressTemp = serviceAddress;
                            responseTime = responseTimeTemp;
                            continue;
                        }

                        if(responseTime > responseTimeTemp){
                            serviceAddressTemp = serviceAddress;
                            responseTime = responseTimeTemp;
                        }

                    }
                }
                return serviceAddressTemp;
//                // 若存在多个地址，则随机获取一个地址
//                address = addressList.get(ThreadLocalRandom.current().nextInt(size));
//                System.out.println("get random address node: "+ address);
            }
            // 获取 address 节点的值
            String addressPath = servicePath + "/" + address;
            return zkClient.readData(addressPath);
        } finally {
//            zkClient.close();
        }
    }

    @Override
    public String getServiceResponseInfo(String serviceName, String serviceAddress) {
        try {
            // 获取 service 节点
            String responsePath = ZK_REGISTRY_PATH + "/" + serviceName+"-response"+"/"+serviceAddress;
            if (!zkClient.exists(responsePath)) {
                return null;
            }
            return zkClient.readData(responsePath);

        }catch (Exception ex){
            ex.printStackTrace();
        }finally {
//            zkClient.close();
        }
        return null;
    }

    @Override
    public void deleteNode(String serviceName, String serviceAddress) {
        try {
            // 获取 service 节点
            String responsePath = ZK_REGISTRY_PATH + "/" + serviceName+"-response"+"/"+serviceAddress;
            if (!zkClient.exists(responsePath)) {
                return;
            }
            zkClient.delete(responsePath);
            System.out.println("---------------->deleteNode :"+responsePath);

        }finally {
//            zkClient.close();
        }
    }
}